package com.zzs.server.dao.redis;

import com.zzs.common.core.constant.RedisKeyConsts;
import com.zzs.common.core.entity.redis.ProblemCache;
import com.zzs.common.core.util.SnowflakeUtil;
import com.zzs.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * @author zzs
 * @date 2025/03/25
 */
@Repository
public class ProblemCacheManager {
    @Autowired
    private RedisService redisService;

    public void save(ProblemCache problemCache) {
        long problemId = problemCache.getId();
//        保存题目缓存
        String problemKey = RedisKeyConsts.getProblemKey(problemId);
        redisService.saveValue(problemKey, problemCache);
//        把题目id存起来(包含全部题目id的zset, 值和分数都是id)
        redisService.saveForZset(RedisKeyConsts.getProblemIdZsetKey(null), problemId, SnowflakeUtil.getTimestampFromId(problemId));
//        根据难度, 再存到对应的zset(存到相应难度的zset, 值和分数都是id)
        redisService.saveForZset(RedisKeyConsts.getProblemIdZsetKey(problemCache.getDifficulty()), problemId, SnowflakeUtil.getTimestampFromId(problemId));
    }

    public void remove(long problemId) {
        String problemKey = RedisKeyConsts.getProblemKey(problemId);
        ProblemCache problemCache = redisService.getValue(problemKey, ProblemCache.class);
//        删除题目详情缓存
        redisService.removeKey(problemKey);
//        在对应的zset中删除相应的id
        int difficulty = problemCache.getDifficulty();
        redisService.removeFromZset(RedisKeyConsts.getProblemIdZsetKey(null), problemId);
        redisService.removeFromZset(RedisKeyConsts.getProblemIdZsetKey(difficulty), problemId);
    }
}
